import type { ConversationItem } from 'vue-element-plus-x/types/Conversations';

import type { MyAgentListType } from '#/api/agent/model/listModel';
import type { BaseListReq } from '#/api/model/baseModel';

import { ref, type Ref } from 'vue';

// 类型
interface MenuTestItemsType extends MyAgentListType {
  id: number;
  key: number;
  label: string;
  messageCount: number;
  [key: string]: any;
}

// 接受的参数类型
interface OptionsType {
  request: (...arg: any) => Promise<any>; // 请求列表数据
  isLoadMoredata: boolean; // 是否要加载更多
  [key: string]: any; // 其他属性
}

// 处理聊天侧边列表Hook
export const useConversations = (options: OptionsType) => {
  const { request, isLoadMoredata, isLoading } = options;
  const data = ref<ConversationItem<MenuTestItemsType>[]>([]); // 列表数据

  // 加载更多数据
  const loadMoreItems = async () => {
    const lastId = data.value[data.value.length - 1]?.key;
    const lastConTime = data.value[data.value.length - 1]?.lastConverseTime;

    if (!isLoadMoredata) return; // 不分页加载更多数据
    if (isLoading.value) return; // 如果正在加载，直接返回

    isLoading.value = true;

    const res: any = await request({
      page: 1,
      pageSize: 10,
      lastId,
      lastConTime,
    });
    // 数据处理
    const newdata =
      res.data &&
      res.data?.map((item: MyAgentListType) => ({
        id: item.id,
        key: item.id,
        isStarred: item.isStarred,
        lastConverseTime: item.lastConverseTime,
        label: item.nickname,
        createdAt: item.createdAt,
        messageCount: item.unreadMsgCount ?? item?.extData?.unreadMsgCount,
      }));

    // 处理加载后没有返回数据的情况
    if (res.data === null) {
      ElMessage({
        message: '没有更多数据了',
        type: 'info',
      });
      isLoading.value = true;
    } else {
      // 更安全的数据合并方式 - 防止重复
      const existingKeys = new Set(
        data.value.map((item: MenuTestItemsType) => item.key),
      );
      const uniqueNewData = newdata?.filter(
        (item: any) => !existingKeys.has(item.key),
      );

      if (uniqueNewData?.length > 0) {
        data.value = [...data.value, ...uniqueNewData];
      }
      isLoading.value = false;
    }
  };

  // 重新刷新
  const refresh = async (params: BaseListReq) => {
    data.value = [];
    await initData(request, data, params);
  };

  // 更新新星标属性
  const updateStared = async (Data: MenuTestItemsType) => {
    data.value.forEach((item: MenuTestItemsType) => {
      if (item.id === Data.id) {
        item.isStarred = !item.isStarred;
      }
    });
  };

  // 取消消息数量
  const updatemsgcount = (id: any, value: any) => {
    data.value.forEach((item) => {
      if (item.id === id) {
        item.messageCount = value;
      }
    });
  };
  // 追加置顶数据
  const addTopData = async (Data: ConversationItem<MenuTestItemsType>[]) => {
    data.value = [...Data, ...data.value];
  };

  // 数据初始化
  onMounted(async () => {
    await initData(request, data);
  });

  return {
    isLoading,
    data,
    loadMoreItems,
    refresh,
    addTopData,
    updateStared,
    updatemsgcount,
  };
};

// 统一的数据加载方法
async function initData(
  request: (...arg: any) => Promise<any>,
  data: Ref<ConversationItem<MenuTestItemsType>[]>,
  params?: any,
) {
  try {
    const res = await request({
      page: 1,
      pageSize: 20,
      ...params,
    });
    data.value = [];

    data.value = res.data.map((item: MyAgentListType) => ({
      id: item.id,
      key: item.id,
      label: item.nickname,
      lastConverseTime: item.lastConverseTime,
      isStarred: item.isStarred,
      createdAt: item.createdAt,
      messageCount: item.unreadMsgCount ?? item?.extData?.unreadMsgCount,
    }));
  } catch (error) {
    console.error('数据加载失败:', error);
    data.value = []; // 出错时清空数据
  }
}
